package com.ywb;

import com.alibaba.fastjson.JSON;
import com.ywb.entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.engine.Engine;

/**
 * @Author ywb
 */
public class ESDocClient {
    public static void main(String[] args) throws Exception{
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

    //    create
        IndexRequest indexRequest = new IndexRequest("java-demo").id("0001");

        User user = new User().setAge(30).setName("张三");
        String userJson = JSON.toJSONString(user);
        indexRequest.source(userJson, XContentType.JSON);

        System.out.println(esClient.index(indexRequest, RequestOptions.DEFAULT).getResult().toString());



    //    update part
        UpdateRequest updateRequest = new UpdateRequest().index("java-demo").id("0001");
        updateRequest.doc(XContentType.JSON, "age", "90");

        UpdateResponse update = esClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.getResult().toString());

    //    Retrieve
        GetRequest getRequest = new GetRequest("java-demo").id("0001");

        GetResponse getResponse = esClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(getResponse.getSourceAsString());

    //    Delete
        DeleteRequest deleteRequest = new DeleteRequest("java-demo").id("0001");

        String result = esClient.delete(deleteRequest, RequestOptions.DEFAULT).getResult().toString();
        System.out.println(result);

        esClient.close();
    }
}
